//
//  CCLoginViewModel.m
//  Party
//
//  Created by coco on 15/4/7.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCLoginViewModel.h"
#import "CCLoginModel.h"
#import "AFHTTPRequestOperationManager+RACSupport.h"
#import <ReactiveMantle/RACSignal+Mantle.h>

@interface CCLoginViewModel ()
@property (strong, nonatomic) CCLoginModel *model;
@property (strong, nonatomic) id<RACSubscriber> loginSubscriber;
@end

@implementation CCLoginViewModel

- (id) initWithModel:(CCLoginModel *)model {
  if (self = [super init]) {
    _model = model;
    [self setupCommand];
    [self setupProperty];
    [self setupSignal];
  }
  return self;
}

- (void) setupSignal {
  @weakify(self);
  self.loginSignal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    @strongify(self);
    self.loginSubscriber = subscriber;
    return [RACDisposable disposableWithBlock:^{
      
    }];
  }];
}
- (RACSignal *) enableSignal {
  return [RACSignal combineLatest:@[RACObserve(self, name),
                             RACObserve(self, password)
                             ]
                    reduce:^(NSString *name, NSString *password){
    return @(name.length > 0 && password.length > 0);
  }];
}

- (void) setupCommand {
  @weakify(self);
  self.loginCommand = [[RACCommand alloc] initWithEnabled: nil
                                              signalBlock:^RACSignal *(id input) {
                                                @strongify(self);
                                                [self.loginSubscriber sendNext:nil];
                                                [[self.model login] subscribeNext:^(id x) {
                                                  NSLog(@"x:%@",x);
                                                  [self.loginSubscriber sendNext:x];
                                                } error:^(NSError *error) {
                                                  [self.loginSubscriber sendError: error];
                                                  NSLog(@"%@",error);
                                                } completed:^{
                                                  [self.loginSubscriber sendCompleted];
                                                  NSLog(@"completed");
                                                  [self.model loginComplate];
                                                }];
                                                return [self.model login];
                                              }];
  
}

- (void) setupProperty {
  _namehold = @"手机号/用户名";
  _passwordhold = @"清输入密码";
}

- (void) dealloc {
  NSLog(@"loginviewmodel dealloc");
}
@end
